<?php
// 启用错误显示
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 捕获所有输出
ob_start();

try {
    // 设置响应头
    header('Content-Type: application/json');
    
    // 加载配置
    require_once '../config/database.php';
    
    // 简单的会话检查
    session_start();
    $user_id = $_SESSION['user_id'] ?? 0;
    
    if (!$user_id) {
        throw new Exception('未登录');
    }
    
    // 获取参数 - 简化为只接受POST
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? '';
    
    // 基本验证
    if ($amount <= 0) {
        throw new Exception('充值金额必须大于0');
    }
    
    if (empty($payment_method)) {
        throw new Exception('请选择支付方式');
    }
    
    // 生成随机码
    $random_code = sprintf('%04d', mt_rand(1000, 9999));
    
    // 创建简单的记录
    $stmt = $pdo->prepare("
        INSERT INTO deposit_records 
        (user_id, amount, payment_method, random_code, status, created_at) 
        VALUES (?, ?, ?, ?, 'pending', NOW())
    ");
    
    $stmt->execute([$user_id, $amount, $payment_method, $random_code]);
    $deposit_id = $pdo->lastInsertId();
    
    // 成功响应
    $response = [
        'success' => true,
        'message' => '充值申请已创建',
        'deposit_id' => $deposit_id,
        'random_code' => $random_code,
        'amount' => $amount
    ];
    
    // 清除缓冲区并输出JSON
    ob_end_clean();
    echo json_encode($response);
    
} catch (Exception $e) {
    // 记录错误
    error_log("充值错误: " . $e->getMessage());
    
    // 清除缓冲区
    ob_end_clean();
    
    // 返回错误响应
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
